#!/usr/bin/env python

# replaceaudio.py - replace audio in a video with that from an external file
# Based on makevid.py by Sam Peterson
# (c) Emlyn O'Regan 2009

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

"""
replaceaudio.py by Emlyn O'Regan <emlynoregan@gmail.com>

Requirements: mencoder

This script replaces audio in a video with that from an external file. It takes three arguments: the input video, the replacement sound file, and the output video.
"""

import os, sys

fps = 30

arglen = len(sys.argv)
if arglen < 3 or arglen > 4:
    print "Usage: replaceaudio.py sourcefile replacementaudiofile [audioout]"
    sys.exit(1)

needexit = False

if arglen >= 4 and os.path.exists(sys.argv[3]):
    print "%s already exists" % sys.argv[3]
    needexit = True

if needexit: sys.exit(1);

outputpath = "output.avi"
if arglen >= 4:
    outputpath = sys.argv[3]

# mencoder_cmd = ('mencoder "%s" -ss %s:%s:%s -endpos %s:%s:%s -ovc xvid -xvidencopts bitrate=4400 -oac mp3lame -o "%s"') \
# mencoder -ovc copy -audiofile soundtrack.mp3 -oac copy video_nosound.avi -o video_new.avi

mencoder_cmd = ('mencoder "%s" -ni -audiofile "%s" -ovc copy -oac copy -o "%s"') \
% (sys.argv[1], sys.argv[2], outputpath)

print "Starting mencoder"
print ("cmd: %s") % (mencoder_cmd)
if os.system(mencoder_cmd) == 0:
    print ("Conversion is complete, output written to %s") % (outputpath)
else:
    print ("Conversion failed, halting")
sys.exit(1)

